package com.flame.system.tools.service;

import com.flame.system.tools.controller.vo.ServerVo;
import com.flame.system.tools.entity.Server;
import com.flame.system.tools.exception.ServerExceptionMessage;
import com.flame.system.tools.exception.ServerRuntimeException;
import com.flame.system.tools.mapper.ServerMapper;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * flame_monitor_server 主机信息表
 *
 * @author 吴欣童
 * @since 2022-11-24 21:48:13
 */
@Service
public class ServerService {

    @Autowired
    private ServerMapper serverMapper;

    public List<Server> pageServer(ServerVo serverVo) {
        return serverMapper.page(serverVo);
    }

    public void addServer(Server server) {
        Server param = serverMapper.selectById(server.getServerName());
        if (param != null) {
            throw new ServerRuntimeException(ServerExceptionMessage.SERVER_EXIST);
        }
        serverMapper.insert(server);
    }

    public void updateServer(Server server) {
        serverMapper.updateById(server);
    }

    public void deleteServer(Server server) {
        serverMapper.deleteById(server.getServerName());
    }

    public void testServerConnection(Server server) {
        try {
            JSch jSch = new JSch();
            Session session = jSch.getSession(server.getServerUsername(), server.getServerHost(), server.getServerPort());
            session.setPassword(server.getServerPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect(10000);
            session.disconnect();
        } catch (JSchException e) {
            throw new ServerRuntimeException(ServerExceptionMessage.CONNECTION_FAILED, e);
        }
    }
}
